package com.ctech.wsgen.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ctech.wsgen.dao.SiteDao;
import com.ctech.wsgen.model.ItemCategory;
import com.ctech.wsgen.model.Manufacture;
import com.ctech.wsgen.model.Site;
import com.ctech.wsgen.writer.ItemCategoryDom4JHtmlWriter;
import com.ctech.wsgen.writer.ItemCategoryListingDom4JHtmlWriter;
import com.ctech.wsgen.writer.ManufactureDom4JHtmlWriter;
import com.ctech.wsgen.writer.ManufactureListingDom4JHtmlWriter;

public class SiteBuilder {

	private static final String CONFIG_WSGEN_CORE_CONTEXT_XML = "config//wsgen-core-context.xml";

	private Logger log = Logger.getLogger(SiteBuilder.class.getName());

	private Site site;
	private SiteDao siteDao;
	
	public static void main(String[] args) throws Exception {
		SiteBuilder siteBuilder = null;
		
		System.out.println("Website Generation Started...\n");
		
		List<String> websites = new ArrayList<String>();
		for (int i = 0; i < args.length; i++) {
			websites.add(args[i]);
		}
		// amerisponse ClosedCircuitTelevision iAccessControl iBurglarAlarms iCentralVac iFireAlarms iHomeAV iIntercom iPagingSystems iTelephoneSupply LowVoltageHT

		for (String website : websites) {
			System.out.println("Generating " + website + " website...");
			siteBuilder = new SiteBuilder(CONFIG_WSGEN_CORE_CONTEXT_XML, "config//" + website + "//" + website + "-context.xml");
			siteBuilder.createSite();
			System.out.println("Generating " + website + " website done.\n");
		}

		System.out.println("\nWebsite Generation Finished.");
		
	}

	public SiteBuilder(String arg0, String arg1) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				new String[] { arg0, arg1 });

		this.site = (Site) ctx.getBean("site");
		this.siteDao = (SiteDao) ctx.getBean("siteDaoJdbc");

		if(log.isInfoEnabled()){
			log.info("==============================================================================");
			log.info("Creating site in this directory = " + site.getStr_siteDir());
			log.info("==============================================================================");
		}
	}

	public void setSite(Site site) {
		this.site = site;
	}

	public void setSiteDao(SiteDao siteDao) {
		this.siteDao = siteDao;
	}

	public void createSite() throws Exception {
		if (this.site != null && this.siteDao != null) {

			if(log.isInfoEnabled()){
				log.info("==========================");
				log.info("Generating Item Category Pages");
				log.info("==========================");
			}
			queryItemCategories();
			makeItemCategoriesWithItemsList();
			createItemCategoryHtml();
			createItemCategoryListingHtml();

			if(log.isInfoEnabled()){
				log.info("==========================");
				log.info("Generating Manufacture Pages");
				log.info("==========================");
			}
			queryManufactures();
			makeManufacturesWithItemsList();
			createManufacturesHtml();
			createManufacturesListingHtml();
			
			if(log.isInfoEnabled()) log.info("Finished creating " + site.getStr_websiteUrl() + " \n");
		}
	}

	public void queryManufactures() throws Exception {
		if(log.isInfoEnabled()) log.info("Quering Manufactures...");
		this.site.setManufactures(this.siteDao.queryManufactures(this.site));
		if(log.isInfoEnabled()) log.info("Number of Items queried for all Manufactures = " + this.site.getManufactures().size());
	}

	public void queryItemCategories() throws Exception {
		if(log.isInfoEnabled()) log.info("Quering Item Categories...");
		this.site.setItemCategories(this.siteDao.queryItemCategories(this.site));
		if(log.isInfoEnabled()) log.info("Number of Items queried for all Item Categories = " + this.site.getItemCategories().size());
	}

	public void makeItemCategoriesWithItemsList() throws Exception {
		if(log.isInfoEnabled()) log.info("Making Item Categories with Items List...");
		List<ItemCategory> itemCategories = this.site.getItemCategories();
		List<ItemCategory> newItemCategories = new ArrayList<ItemCategory>();

		ItemCategory ic = itemCategories.get(0);
		String uniqueName = ic.getUniqueName();
		int countItemsWithNoPrice = 0;
		for (ItemCategory itemCategory : itemCategories) {
			if (!uniqueName.equals(itemCategory.getUniqueName())) {
				newItemCategories.add(ic);
				uniqueName = itemCategory.getUniqueName();
				ic = itemCategory;
			}
			ic.getItems().add(itemCategory.getAsItem());
			if (itemCategory.getAsItem().getPrice() == null
					|| itemCategory.getAsItem().getPrice().doubleValue() <= 0) {
				countItemsWithNoPrice++;
				if(log.isDebugEnabled()) log.debug("*** No Price - " + itemCategory.getAsItem().toString());
			}
		}
		newItemCategories.add(ic);
		this.site.setItemCategories(newItemCategories);
		if(log.isDebugEnabled()) log.debug("Number of Items with no price = " + countItemsWithNoPrice);
	}

	public void makeManufacturesWithItemsList() {
		if(log.isInfoEnabled()) log.info("Making Manufactures with Items List...");
		List<Manufacture> manufactures = this.site.getManufactures();
		List<Manufacture> newmanufactures = new ArrayList<Manufacture>();

		Manufacture manu = manufactures.get(0);
		String uniqueName = manu.getUniqueName();
		int countItemsWithNoPrice = 0;
		for (Manufacture manufacture : manufactures) {
			if (!uniqueName.equals(manufacture.getUniqueName())) {
				newmanufactures.add(manu);
				uniqueName = manufacture.getUniqueName();
				manu = manufacture;
			}
			manu.getItems().add(manufacture.getAsItem());
			if (manufacture.getAsItem().getPrice() == null
					|| manufacture.getAsItem().getPrice().doubleValue() <= 0) {
				countItemsWithNoPrice++;
				if(log.isDebugEnabled()) log.debug("*** No Price - " + manufacture.getAsItem().toString());
			}
		}
		newmanufactures.add(manu);
		this.site.setManufactures(newmanufactures);
		if(log.isDebugEnabled()) log.debug("Number of Items with no price = " + countItemsWithNoPrice);
	}

	public void createManufacturesHtml() throws Exception {
		List<Manufacture> manufactures = this.site.getManufactures();
		if (manufactures != null && manufactures.size() != 0) {
			if(log.isInfoEnabled()) log.info("Number of Manufactures = " + manufactures.size());
			for (Manufacture manufacture : manufactures) {
				new ManufactureDom4JHtmlWriter(manufacture, this.site);
			}
		} else {
			log.error("No Manufactures to create HTML");
		}
	}

	public void createItemCategoryHtml() throws Exception {
		List<ItemCategory> itemCategories = this.site.getItemCategories();
		if (itemCategories != null && itemCategories.size() != 0) {
			if(log.isInfoEnabled()) log.info("Number of Item Category = " + itemCategories.size());
			for (ItemCategory itemCategory : itemCategories) {
				new ItemCategoryDom4JHtmlWriter(itemCategory, this.site);
			}
		} else {
			log.error("No ItemCategory to create HTML");
		}
	}

	public void createManufacturesListingHtml() throws Exception {
		List<Manufacture> manufactures = this.site.getManufactures();
		if (manufactures != null && manufactures.size() != 0) {
			if(log.isInfoEnabled()) log.info("Number of Manufactures = " + manufactures.size());
			new ManufactureListingDom4JHtmlWriter(manufactures, this.site);
		} else {
			log.error("No Manufactures to create HTML");
		}
	}

	public void createItemCategoryListingHtml() throws Exception {
		List<ItemCategory> itemCategories = this.site.getItemCategories();
		if (itemCategories != null && itemCategories.size() != 0) {
			if(log.isInfoEnabled()) log.info("Number of ItemCategory = " + itemCategories.size());
			Collections.sort(itemCategories);
			new ItemCategoryListingDom4JHtmlWriter(itemCategories, this.site);
		} else {
			log.error("No ItemCategory to create HTML");
		}
	}

}
